package com.mce.nebula.controller;

import com.mce.nebula.dto.ApiResponse;
import com.mce.nebula.dto.AppGroupCreateRequest;
import com.mce.nebula.dto.AppGroupResponse;
import com.mce.nebula.entity.AppGroup;
import com.mce.nebula.entity.Team;
import com.mce.nebula.security.UserDetailsImpl;
import com.mce.nebula.service.AppGroupService;
import com.mce.nebula.service.TeamService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 应用组管理控制器
 */
@Slf4j
@RestController
@RequestMapping("/api/teams/{teamName}/groups")
@Tag(name = "应用组管理", description = "应用组管理相关接口")
@RequiredArgsConstructor
public class AppGroupController {
    
    private final AppGroupService appGroupService;
    private final TeamService teamService;
    
//    @PostMapping
//    @Operation(summary = "创建应用组", description = "在指定团队下创建新的应用组")
//    public ResponseEntity<ApiResponse<AppGroupResponse>> createAppGroup(
//            @PathVariable String teamName,
//            @Valid @RequestBody AppGroupCreateRequest request,
//            Authentication authentication) {
//        try {
//            // 获取团队信息
//            Team team = teamService.findByTeamName(teamName)
//                .orElseThrow(() -> new RuntimeException("团队不存在"));
//
//            // 获取用户信息
//            UserDetailsImpl userDetails = (UserDetailsImpl) authentication.getPrincipal();
//            Integer userId = userDetails.getId().intValue();
//            String enterpriseId = userDetails.getEnterpriseId();
//
//            // 检查用户是否在团队中
//            if (!teamService.isUserInTeam(team.getTenantId(), userId)) {
//                throw new RuntimeException("用户不在该团队中");
//            }
//
//            AppGroup appGroup = appGroupService.createAppGroup(request, team.getTenantId(), userId, enterpriseId);
//            return ResponseEntity.ok(ApiResponse.success(new AppGroupResponse(appGroup), "应用组创建成功"));
//        } catch (Exception e) {
//            log.error("Failed to create app group: {} in team: {}", request.getGroupName(), teamName, e);
//            return ResponseEntity.badRequest()
//                .body(ApiResponse.error(400, e.getMessage()));
//        }
//    }
    
//    @GetMapping
//    @Operation(summary = "获取应用组列表", description = "获取团队下的所有应用组")
//    public ResponseEntity<ApiResponse<List<AppGroupResponse>>> getAppGroups(
//            @PathVariable String teamName,
//            Authentication authentication) {
//        try {
//            // 获取团队信息
//            Team team = teamService.findByTeamName(teamName)
//                .orElseThrow(() -> new RuntimeException("团队不存在"));
//
//            // 获取用户信息
//            UserDetailsImpl userDetails = (UserDetailsImpl) authentication.getPrincipal();
//            Integer userId = userDetails.getId().intValue();
//
//            // 检查用户是否在团队中
//            if (!teamService.isUserInTeam(team.getTenantId(), userId)) {
//                throw new RuntimeException("用户不在该团队中");
//            }
//
//            List<AppGroup> appGroups = appGroupService.getTenantAppGroups(team.getTenantId());
//            List<AppGroupResponse> responses = appGroups.stream()
//                .map(AppGroupResponse::new)
//                .collect(Collectors.toList());
//
//            return ResponseEntity.ok(ApiResponse.success(responses));
//        } catch (Exception e) {
//            log.error("Failed to get app groups for team: {}", teamName, e);
//            return ResponseEntity.badRequest()
//                .body(ApiResponse.error(400, e.getMessage()));
//        }
//    }
    
//    @GetMapping("/{groupId}")
//    @Operation(summary = "获取应用组详情", description = "获取指定应用组的详细信息")
//    public ResponseEntity<ApiResponse<AppGroupResponse>> getAppGroup(
//            @PathVariable String teamName,
//            @PathVariable String groupId,
//            Authentication authentication) {
//        try {
//            // 获取团队信息
//            Team team = teamService.findByTeamName(teamName)
//                .orElseThrow(() -> new RuntimeException("团队不存在"));
//
//            // 获取用户信息
//            UserDetailsImpl userDetails = (UserDetailsImpl) authentication.getPrincipal();
//            Integer userId = userDetails.getId().intValue();
//
//            // 检查用户是否在团队中
//            if (!teamService.isUserInTeam(team.getTenantId(), userId)) {
//                throw new RuntimeException("用户不在该团队中");
//            }
//
//            AppGroup appGroup = appGroupService.findByGroupId(groupId)
//                .orElseThrow(() -> new RuntimeException("应用组不存在"));
//
//            // 检查应用组是否属于该团队
//            if (!appGroup.getTenantId().equals(team.getTenantId())) {
//                throw new RuntimeException("应用组不属于该团队");
//            }
//
//            return ResponseEntity.ok(ApiResponse.success(new AppGroupResponse(appGroup)));
//        } catch (Exception e) {
//            log.error("Failed to get app group: {} in team: {}", groupId, teamName, e);
//            return ResponseEntity.badRequest()
//                .body(ApiResponse.error(400, e.getMessage()));
//        }
//    }
    
//    @PutMapping("/{groupId}")
//    @Operation(summary = "更新应用组", description = "更新应用组信息")
//    @PreAuthorize("hasRole('ADMIN') or @teamService.isTeamAdmin(#teamName, authentication.principal.id)")
//    public ResponseEntity<ApiResponse<AppGroupResponse>> updateAppGroup(
//            @PathVariable String teamName,
//            @PathVariable String groupId,
//            @Valid @RequestBody AppGroupCreateRequest request) {
//        try {
//            // 获取团队信息
//            Team team = teamService.findByTeamName(teamName)
//                .orElseThrow(() -> new RuntimeException("团队不存在"));
//
//            AppGroup appGroup = appGroupService.findByGroupId(groupId)
//                .orElseThrow(() -> new RuntimeException("应用组不存在"));
//
//            // 检查应用组是否属于该团队
//            if (!appGroup.getTenantId().equals(team.getTenantId())) {
//                throw new RuntimeException("应用组不属于该团队");
//            }
//
//            AppGroup updatedAppGroup = appGroupService.updateAppGroup(groupId, request);
//            return ResponseEntity.ok(ApiResponse.success(new AppGroupResponse(updatedAppGroup), "应用组更新成功"));
//        } catch (Exception e) {
//            log.error("Failed to update app group: {} in team: {}", groupId, teamName, e);
//            return ResponseEntity.badRequest()
//                .body(ApiResponse.error(400, e.getMessage()));
//        }
//    }
    
//    @DeleteMapping("/{groupId}")
//    @Operation(summary = "删除应用组", description = "删除指定的应用组")
//    @PreAuthorize("hasRole('ADMIN') or @teamService.isTeamAdmin(#teamName, authentication.principal.id)")
//    public ResponseEntity<ApiResponse<Void>> deleteAppGroup(
//            @PathVariable String teamName,
//            @PathVariable String groupId) {
//        try {
//            // 获取团队信息
//            Team team = teamService.findByTeamName(teamName)
//                .orElseThrow(() -> new RuntimeException("团队不存在"));
//
//            AppGroup appGroup = appGroupService.findByGroupId(groupId)
//                .orElseThrow(() -> new RuntimeException("应用组不存在"));
//
//            // 检查应用组是否属于该团队
//            if (!appGroup.getTenantId().equals(team.getTenantId())) {
//                throw new RuntimeException("应用组不属于该团队");
//            }
//
//            appGroupService.deleteAppGroup(groupId);
//            return ResponseEntity.ok(ApiResponse.success(null, "应用组删除成功"));
//        } catch (Exception e) {
//            log.error("Failed to delete app group: {} in team: {}", groupId, teamName, e);
//            return ResponseEntity.badRequest()
//                .body(ApiResponse.error(400, e.getMessage()));
//        }
//    }
}





